const App = {
    mixins: [Save], // 配置文件，路径/utils/mixins.js
    data() {
        return {
            photo,
            category: [], // 视频分类数据
            video_tags: [], // 全部视频标签数据
            themeTags: [], // 题材标签数据（Parent_SerialNumber为VT0000000000017）
            backgroundTags: [], // 时代背景标签数据（Parent_SerialNumber为VT0000000000018）
            childDataForm: [], // 子表表单数据
            dataForm: {
                Row_Status: '2',
                // Theme_Tag_SerialNumber: [], // 多选题材标签
                // Background_Tag_SerialNumber: [], // 多选时代背景标签
                Environment_MicroScreen: '1',
                Environment_BigScreen: '1',
            },
            videos_tags: [],
            loading: false, // 上传加载状态
            Video_Tag_SerialNumber: []
        };
    },
    mounted() {
        // let arr = [{label:'11',value:'aa'},{label:'22',value:'bb'},{label:'33',value:'cc'}];
        // let arr1 = [1,2,3];
        // //1
        // arr1 = arr.map(i=>i.value);//[aa,bb,cc]
        // //2
        // arr.forEach(item=>{
        //     arr1.push(item.value)
        // })
        this.getCategory();
        // this.getVideoTags();
        // 如果是编辑模式，加载已保存的标签
        // if (this.action === 'Modify' && this.nodeKey) {
        //     this.loadSavedTags();
        // }
    },
    watch: {
        // 'dataForm.Video_SerialNumber'(){
        //     this.loadSavedTags();
        // },
        childDataForm(val) {
            
            this.Video_Tag_SerialNumber = val.filter(i=>i.Row_Status != '1').map(i=>i.Video_Tag_SerialNumber);
        }
    },
    methods: {
        // 加载已保存的标签数据
        loadSavedTags() {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'videos_mapping_tags',
                    Condition: `Video_SerialNumber='${this.nodeKey}'`
                },
                success: (data) => {
                    // 分离题材标签和时代背景标签
                    const themeTags = [];
                    const backgroundTags = [];

                    data.forEach(tag => {
                        if (this.themeTags.some(t => t.Video_Tag_SerialNumber === tag.Video_Tag_SerialNumber)) {
                            themeTags.push(tag.Video_Tag_SerialNumber);
                        }
                        if (this.backgroundTags.some(t => t.Video_Tag_SerialNumber === tag.Video_Tag_SerialNumber)) {
                            backgroundTags.push(tag.Video_Tag_SerialNumber);
                        }
                    });

                    // 更新表单数据
                    this.dataForm.Theme_Tag_SerialNumber = themeTags;
                    this.dataForm.Background_Tag_SerialNumber = backgroundTags;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                }
            });
        },


        // 获取视频分类数据
        getCategory() {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'videos_category',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.category = data;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryForObtainingTrees`,
                type: "GET",
                data: {
                    TableName: 'videos_tags',
                    NodeCode: "",
                },
                success: (data) => {
                    console.log(data);
                    this.videos_tags = data;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
        },

        // 获取视频标签数据并分类
        getVideoTags() {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'videos_tags',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.video_tags = data;
                    this.themeTags = data.filter(item => item.Parent_SerialNumber === 'VT0000000000017');
                    this.backgroundTags = data.filter(item => item.Parent_SerialNumber === 'VT0000000000018');
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
        },

        // 返回上一页
        goBack() {
            history.back();
        },

        async handleSubmit() {
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.loading = true;
                let ls_URL = window.location.href;
                const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
                let lJSONObject_Data_Options = new Object();
                lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

                let ls_MainTableName = lJSONObject_Data_Options.TableName;
                let ls_DataForm = lJSONObject_Data_Options.form;
                let ls_primary_key = lJSONObject_Data_Options.primary_key;

                // this.dataForm.Theme_Tag_SerialNumber.forEach(item => {
                //     this.childDataForm.push({
                //         Video_SerialNumber: this.dataForm.Video_SerialNumber,
                //         Video_Tag_SerialNumber: item
                //     })
                // })
                // this.dataForm.Background_Tag_SerialNumber.forEach(item => {
                //     this.childDataForm.push({
                //         Video_SerialNumber: this.dataForm.Video_SerialNumber,
                //         Video_Tag_SerialNumber: item
                //     })
                // })
                if (action == "Add") {
                    this.Video_Tag_SerialNumber.forEach((item) => {
                        this.childDataForm.push({
                            Video_Tag_SerialNumber: item,
                        });
                    });
                } else if (action == "Modify") {
                    this.Video_Tag_SerialNumber.forEach((item) => {
                        let obj = this.childDataForm.filter(i => i.Video_Tag_SerialNumber == item)[0];
                        if (obj) {
                            obj.Row_Status = "0";
                        } else {
                            this.childDataForm.push({
                                Video_SerialNumber: this.dataForm.Video_SerialNumber,
                                Video_Tag_SerialNumber: item,
                            });
                        }
                    });
                    this.childDataForm.forEach((item) => {
                        if (!this.Video_Tag_SerialNumber.some(i => i == item.Video_Tag_SerialNumber)) {
                            item.Row_Status = "1";
                        }
                    });
                }
 
                //  = [...this.dataForm.Theme_Tag_SerialNumber,...this.dataForm.Background_Tag_SerialNumber]
                //没有子表下面内容就会报错，try/catch抛出异常
                try {
                    //可能涉及多个子表
                    document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
                        if (item.hasAttribute('data-options')) {
                            let lJSONObject_ChildData_Options = new Object();
                            lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

                            let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
                            let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
                            // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
                            if (this[ls_DataForm][ls_primary_key]) {
                                this[ls_ChildDataForm].forEach(item => {
                                    item[ls_primary_key] = this[ls_DataForm][ls_primary_key];
                                })
                            }
                            //建立子表结构体
                            let JSONArray_ChildRecord = new Array();
                            JSONArray_ChildRecord = this[ls_ChildDataForm];
                            if (!this[ls_DataForm].Children) {
                                this[ls_DataForm].Children = new Object();
                            }
                            this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
                        }
                    })
                } catch (error) {

                }
                //建立新增提交结构
                let lJSONObject_DataSet = new Object();
                if (action == 'Add') {
                    if (this.nodeKey) {
                        this[ls_DataForm].Parent_SerialNumber = this.nodeKey;
                    }
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(this[ls_DataForm]);
                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
                    lJSONObject_DataSet[action] = lJSONObject_Table;
                } else if (action == 'Modify') {
                    const { add, modify } = this.deal(this[ls_DataForm]);
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(modify);

                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;

                    lJSONObject_DataSet[action] = lJSONObject_Table;
                    lJSONObject_DataSet['Add'] = new Object();
                    if (add != null) {
                        let lJSONArray_Record_Add = new Array();
                        lJSONArray_Record_Add.push(add);

                        let lJSONObject_Table_Add = new Object();
                        lJSONObject_Table_Add[ls_MainTableName] = lJSONArray_Record_Add;

                        lJSONObject_DataSet['Add'] = lJSONObject_Table_Add;
                    }
                }

                console.log(lJSONObject_DataSet);

                let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                    Operation_Type: '0',
                    Operation_Path: this.relativePath,
                    Operation_Main,
                    Operation_Interface: "generalSaveByRequestBody",
                    Operation_IP: getIpAddress()
                }]
                console.log(lJSONObject_DataSet);
                submitSave(lJSONObject_DataSet, (res) => {
                    if (res.Status == 'success') {
                        window.location.href = './index.html'
                    }
                    this.loading = false;
                })
            } else {
                this.$message({
                    message: '存在未填写的必填项！',
                    type: 'warning'
                });
            }
        },

        // 上传成功回调
        success(res) {
            this.dataForm.Video_Path = res.Path;
        },

        // 上传进度回调
        progress(loading) {
            this.loading = loading;
        },

        // 新增标签项（如果需要）
        handleAdd(formName) {
            if (this.action === 'Add') {
                this[formName].push({});
            } else if (this.action === 'Modify') {
                let lJSONObject_Data_Options = new Object();
                lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));
                let ls_primary_key = lJSONObject_Data_Options.primary_key;
                let lJSONObject_Data = new Object();
                lJSONObject_Data[ls_primary_key] = this.nodeKey;
                this[formName].push(lJSONObject_Data);
            }
        },

        // 删除标签项（如果需要）
        handleRemove1(formName) {
            if (this.action === 'Add') {
                if (this[formName].length > 0) {
                    this[formName].pop();
                } else {
                    this.$message({
                        message: '不能再删除了',
                        type: 'warning'
                    });
                }
            } else if (this.action === 'Modify') {
                if (this[formName].filter(item => item.Row_Status != '1').length > 0) {
                    let i = this[formName].filter(item => item.Row_Status != '1').length - 1;
                    let obj = this[formName].filter(item => item.Row_Status != '1')[i];
                    if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                        this[formName].pop();
                    } else {
                        this.$confirm('该操作将删除此条数据,是否继续?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                        }).then(() => {
                            this[formName].filter(item => item.Row_Status != '1')[i].Row_Status = '1';
                        }).catch(() => {
                            this.$message({
                                type: 'warning',
                                message: '已取消删除'
                            });
                        });
                    }
                } else {
                    this.$message({
                        message: '不能再删除了',
                        type: 'warning'
                    });
                }
            }
        },

    }
};

const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });

// 引入全部图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}

app.component('yl-upload', ylUpload);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");